from flask import Flask, render_template,request, session, Blueprint, send_file, send_from_directory
from flask_restful import Resource, Api
from flask_cors import CORS
from flask_babel import Babel
app = Flask(__name__)
api = Api(app)
CORS(app)

app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)

# 1. 创建蓝图
admin_bp = Blueprint('admin', __name__)

app.secret_key = 'supersecretkey'

@app.route('/')
def hello_word():
    return 'Hello World!'


@app.route('/index')
def index():
    return render_template('index.html', name='World')


@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'GET':
        username = request.form['username']
        return f'Hello, {username}!'
    return render_template('form.html')


@app.route('/login', methods=['POST'])
def login():
    session['username'] = request.form['username']
    return 'Login Successful!'

@app.route('/logout')
def logout():
    session.pop('username', None)
    return 'Logout Successful!'


@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    file.save('/path/to/save' + file.filename)
    return 'Upload Successful!'

@app.route('/download')
def download_file():
    return send_file('/path/to/file', as_attachment=True)


@app.route('/download/<filename>')
def download_from_directory(filename):
    return send_from_directory('/path/to/directory', filename, as_attachment=True)



@app.route('/form', methods=['POST'])
def form_handler():
    username = request.form['username']
    return f'Hello, {username}!'

@app.route('/json', methods=['POST'])
def json_handler():
    data = request.json
    return f'Hello, {data["username"]}!'


@admin_bp.route('/admin')
def admin():
    return 'Admin Page'


# 2 注册蓝图
app.register_blueprint(admin_bp)


class helloWorld(Resource):
    def get(self):
        return {'Hello, World!'}


api.add_resource(helloWorld, '/hello')

if __name__ == '__main__':
    app.run()